import 'dart:convert';

import 'package:android_location_mocker/MockLocationBean.dart';
import 'package:android_location_mocker/android_location_mocker.dart';
import 'package:android_location_mocker_example/LocationBean.dart';
import 'package:android_location_mocker_example/toast_util.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'state.dart';

class HomeLogic extends GetxController {
  final HomeState state = HomeState();
  final androidLocationMockerPlugin = AndroidLocationMocker();
  @override
  void onInit() {
    super.onInit();
    init();
  }

  Future<void> init() async {
    var sp = await SharedPreferences.getInstance();
    String? res = await sp.getString("lastLocation");
    if (res == null) return;
    var location = LocationBean.fromJson(jsonDecode(res));
    state.address.value = location.address ?? '';
    List<String> lnglog = "${location.location}".split(",");
    state.current_longitude.value = double.tryParse(lnglog[0]) ?? 0;
    state.current_latitude.value = double.tryParse(lnglog[1]) ?? 0;
  }

  Future<void> search() async {
    try {
      String url =
          "https://restapi.amap.com/v3/place/text?keywords=${Uri.encodeComponent(state.address.value)}&key=${state.key.value}";
      var res = await Dio().get(url);
      var pois = res.data['pois'];
      if (pois is List) {
        state.list.clear();
        state.list.addAll(pois.map((m) => LocationBean.fromJson(m)).toList());
      } else {
        showToast("获取失败:$res");
      }
    } catch (e) {
      print("错误");
      print(e);
      showToast("错误：$e");
    }
  }

  void mock() {
    var bean = MockLocationBean(
        common: Common(
            useGps: state.isUseGps.value,
            useNetwork: state.isUseNetwork.value,
            frequencyMs: int.tryParse(state.frequencyController.value) ?? 100),
        mockLocation: MockLocation(
            lat: state.current_latitude.value,
            lng: state.current_longitude.value));
    androidLocationMockerPlugin.startMock(bean);
  }

  Future<void> stopMock() async {
    await androidLocationMockerPlugin.stopMock();
  }

  Future<void> select(bean) async {
    List<String> lnglog = "${bean.location}".split(",");
    state.current_longitude.value = double.tryParse(lnglog[0]) ?? 0;
    state.current_latitude.value = double.tryParse(lnglog[1]) ?? 0;
    state.address.value = bean.address ?? "";
    state.location.value =
        "${state.current_longitude.value},${state.current_latitude.value}";
    var sp = await SharedPreferences.getInstance();
    await sp.setString("lastLocation", jsonEncode(bean.toJson()));
    showToast(
        "当前已选择：${state.current_latitude.value},${state.current_longitude.value}");
  }
}
